package com.s3.stack;

/*基于数组实现的栈 */
public class ArrayStack {

	protected static final int DEFAULT_LENGTH = 10;

	protected Object[] datas;

	// 栈中元素个数
	protected int used = 0;

	public ArrayStack() {
		this(DEFAULT_LENGTH);
	}

	public ArrayStack(int length) {
		this.datas = new Integer[length];
	}

	// 栈的大小
	public int getLength() {
		return this.datas.length;
	}

	// 入栈操作
	public boolean push(Object value) {
		if (this.used >= this.getLength()) {
			return false;
		}
		this.datas[this.used] = value;
		this.used++;
		return true;
	}

	// 出栈操作
	public Object pop() {
		if (this.used <= 0) {
			return null;
		}
		this.used--;
		Object ret = this.datas[used];
		this.datas[this.used] = null;
		return ret;
	}

	@Override
	public String toString() {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("arrayStack = [");
		for (int i = this.used - 1; i >= 0; i--) {
			stringBuilder.append(this.datas[i]);
			if (i == 0) {
				continue;
			}
			stringBuilder.append(", ");
		}
		stringBuilder.append(']');
		return stringBuilder.toString();
	}

	public static void main(String[] args) {
		ArrayStack stack = new ArrayStack(3);
		System.out.println(stack.push(1));
		System.out.println(stack.push(2));
		System.out.println(stack.push(3));
		System.out.println(stack.push(5));
		System.out.println(stack);

		System.out.println(stack.pop());
		System.out.println(stack);

		System.out.println(stack.pop());
		System.out.println(stack);
		
		System.out.println(stack.pop());
		System.out.println(stack);
	}

}
